<?php

namespace common\wodrow;

class Rsa
{
    private $config = [
        'public_key' => '',
        'private_key' => '',
    ];

    public function __construct($privateKeyFilepath, $publicKeyFilepath)
    {
        $this->config['private_key'] = $this->getContents($privateKeyFilepath);
        $this->config['public_key'] = $this->getContents($publicKeyFilepath);
    }

    /**
     * @param $filePath string
     * @return bool|string
     * @uses 获取文件内容
     */
    private function getContents($filePath)
    {
        file_exists($filePath) or die ('密钥或公钥的文件路径错误');
        return file_get_contents($filePath);
    }

    /**
     * @return bool|resource
     * @uses 获取私钥
     */
    private function getPrivateKey()
    {
        $privKey = $this->config['private_key'];
        return openssl_pkey_get_private($privKey);
    }

    /**
     * @return bool|resource
     * @uses 获取公钥
     */
    private function getPublicKey()
    {
        $publicKey = $this->config['public_key'];
        return openssl_pkey_get_public($publicKey);
    }

    /**
     * @param string $data
     * @return null|string
     * @uses 私钥加密
     */
    public function privEncrypt($data = '')
    {
        if (!is_string($data)) {
            return null;
        }
        return openssl_private_encrypt($data, $encrypted, $this->getPrivateKey()) ? base64_encode($encrypted) : null;
    }

    /**
     * @param string $data
     * @return null|string
     * @uses 公钥加密
     */
    public function publicEncrypt($data = '')
    {
        if (!is_string($data)) {
            return null;
        }
        return openssl_public_encrypt($data, $encrypted, $this->getPublicKey()) ? base64_encode($encrypted) : null;
    }

    /**
     * @param string $encrypted
     * @return null
     * @uses 私钥解密
     */
    public function privDecrypt($encrypted = '')
    {
        if (!is_string($encrypted)) {
            return null;
        }
        return (openssl_private_decrypt(base64_decode($encrypted), $decrypted, $this->getPrivateKey())) ? $decrypted : null;
    }

    /**
     * @param string $encrypted
     * @return null
     * @uses 公钥解密
     */
    public function publicDecrypt($encrypted = '')
    {
        if (!is_string($encrypted)) {
            return null;
        }
        return (openssl_public_decrypt(base64_decode($encrypted), $decrypted, $this->getPublicKey())) ? $decrypted : null;
    }
}
